package com.example.myapp;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;

import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

//设备
public class EquipmentActivity extends AppCompatActivity {
    ImageButton btn_flame,btn_smog,btn_fan,btn_buzzer,btn_water_pump;
    TextView txt_flame,txt_smoke,txt_fan,txt_buzzer,txt_pump;
    //_______________________________________________________________________
    private String mqtt_sub_topic = "/k1g4ohPpMe7/APP_demo/user/get";          //需要订阅的主题   接受数据
    private String mqtt_pub_topic = "/sys/k1g4ohPpMe7/APP_demo/thing/event/property/post";         //需要发布的主题   发送数据
    private MqttClient mqtt_client;                         //创建一个mqtt_client对象
    MqttConnectOptions options;                             //连接帮助对象
    Handler handler;

    String jsonString;                         //订阅的json数据
    int flameValue;                            //火焰状态
    int smokeValue;                            //烟雾状态
    int fanValue;                              //风扇状态
    int buzzerValue;                           //蜂鸣器状态
    int PumpValue;                             //水泵状态

    @SuppressLint("HandlerLeak")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_equipment);

        //绑定控件
        initView();
        //按钮单击事件,火焰
        btnFlame();
        //烟雾
        btnSmog();
        //风扇
        btnFan();
        //蜂鸣器
        btnBuzzer();
        //水泵
        btnWater();

//________________________________________________//
        //开始连接
        mqtt_init_Connect();
        startReconnect();

        handler=new Handler(){
            @Override
            public void handleMessage(@NonNull Message msg) {
                super.handleMessage(msg);
                switch (msg.what){
                    case 1:         //开机校验更新回传
                        break;
                    case 2:         //反馈回传
                        break;
                    case 3:         //mqtt收到消息回传
                        //makeToast(msg.obj.toString());                  //msg.obj.toString()==     "/k1g4ohPpMe7/APP_demo/user/get---{\"deviceType\":\"CustomCategory\",\"iotId\":\"6KQCL6evcUOs98LFGm0Fk1g4o0\",\"requestId\":\"421321722\",\"checkFailedData\":{},\"productKey\":\"k1g4ohPpMe7\",\"gmtCreate\":1718896026921,\"deviceName\":\"MQTT_stm32\",\"items\":{\"SprayPumpStatus\":{\"time\":1718896026917,\"value\":0},\"SmokeSensorState\":{\"time\":1718896026917,\"value\":0},\"FanRun\":{\"time\":1718896026917,\"value\":0},\"Buzzer\":{\"time\":1718896026917,\"value\":0},\"Flame_State\":{\"time\":1718896026917,\"value\":0}}}"
                        //获取数据
                        jsonString = msg.obj.toString();                  //接受的消息
                        // 提取JSON数据
                        String jsonstr = extractJson(jsonString);
                        //获取有效数据并|显示show|
                        getJString(jsonstr);
                        break;
                    case 30:         //连接失败
                        Toast.makeText(EquipmentActivity.this,"连接失败", Toast.LENGTH_LONG).show();
                        break;
                    case 31:         //连接成功
                        Toast.makeText(EquipmentActivity.this,"连接成功", Toast.LENGTH_LONG).show();
                        try {//mqtt_client.subscribe(mqtt_sub_topic,1);
                            mqtt_client.subscribe(mqtt_sub_topic);              //订阅消息subscribe
                        } catch (MqttException e) {
                            throw new RuntimeException(e);
                        }
                        break;
                    default:

                }
            }
            // 从混合字符串中提取JSON数据,变成String类型
            private String extractJson(String mixedString) {
                Pattern pattern = Pattern.compile("\\{.*\\}");
                Matcher matcher = pattern.matcher(mixedString);
                if (matcher.find()) {
                    return matcher.group();
                }
                return null;
            }
            //获取将JSON数据转化为有效数据   已转换的String数据中截取有效值，并显示show_value
            @SuppressLint("SetTextI18n")
            private void getJString(String jsonString) {
                // 解析JSON数据
                try {
                    // 将JSON字符串转换为Java对象
                    JSONObject jsonObject = new JSONObject(jsonString);
                    // 获取Flame_State的值
                    JSONObject items = jsonObject.getJSONObject("items");
                    //JSONObject flameStateObject = items.getJSONObject("Flame_State");  中间转换.getInt简写了
                    flameValue = items.getJSONObject("Flame_State").getInt("value");
                    smokeValue = items.getJSONObject("SmokeSensorState").getInt("value");
                    fanValue = items.getJSONObject("FanRun").getInt("value");
                    buzzerValue = items.getJSONObject("Buzzer").getInt("value");
                    PumpValue = items.getJSONObject("SprayPumpStatus").getInt("value");
                    //显示在app状态栏中
                    show_value();
                    // 打印结果
                    Log.d("JSONParser", "Flame State Value: " + flameValue);
                    Log.d("JSONParser", "SmokeSensor State Value: " + smokeValue);
                    Log.d("JSONParser", "SprayPump State Value: " + PumpValue);
                    Log.d("JSONParser", "FanRun State Value: " + fanValue);
                    Log.d("JSONParser", "Buzzer Value: " + buzzerValue);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            //显示内容
            private void show_value() {
                if (flameValue==0){
                    txt_flame.setText("无火焰");
                    txt_flame.setTextColor(Color.BLACK); // 设置为黑色
                }else {
                    txt_flame.setTextColor(Color.RED);   // 设置为红色
                    txt_flame.setText("有火焰");
                }
                if (smokeValue==0){
                    txt_smoke.setText("无烟雾");
                    txt_smoke.setTextColor(Color.BLACK);
                }else {
                    txt_smoke.setTextColor(Color.RED);
                    txt_smoke.setText("有烟雾");
                }
                if (fanValue==0){
                    txt_fan.setText("打开");
                    txt_fan.setTextColor(Color.BLUE);
                }else {
                    txt_fan.setTextColor(Color.BLACK);
                    txt_fan.setText("关闭");
                }
                if (buzzerValue==0){
                    txt_buzzer.setTextColor(Color.BLUE);
                    txt_buzzer.setText("打开");
                }else {
                    txt_buzzer.setTextColor(Color.BLACK);
                    txt_buzzer.setText("关闭");
                }
                if (PumpValue==0){
                    txt_pump.setTextColor(Color.BLUE);
                    txt_pump.setText("打开");
                }else {
                    txt_pump.setTextColor(Color.BLACK);
                    txt_pump.setText("关闭");
                }
            }
        };//handler结束
    }//onCreate结束

    private void initView() {
        btn_flame=findViewById(R.id.flame);
        btn_smog=findViewById(R.id.smog);
        btn_fan=findViewById(R.id.fan);
        btn_buzzer=findViewById(R.id.buzzer);
        btn_water_pump=findViewById(R.id.water_pump);
        txt_flame =findViewById(R.id.text_flame);
        txt_smoke =findViewById(R.id.text_smoke);
        txt_fan =findViewById(R.id.text_fan);
        txt_buzzer =findViewById(R.id.text_buzzer);
        txt_pump =findViewById(R.id.text_pump);
    }
    private int fan_flag=1;    //标志位
    private void btnFlame() {
        btn_flame.setOnClickListener(v -> {
            if (fan_flag==0){  //{"method":"thing.service.property.set","id":"421321722","params":{"SprayPumpStatus":0,"FanRun":0,"SmokeSensorState":0,"Flame_State":0,"Buzzer":0},"version":"1.0.0"}
                publishMessage(mqtt_pub_topic,"{\"method\":\"thing.service.property.set\",\"id\":\"421321722\",\"params\":{\"Flame_State\":1},\"version\":\"1.0.0\"}");
                btn_flame.setImageResource(R.drawable.flame2);
                makeToast("开始检测火焰");
                fan_flag=1;
            }else {
                publishMessage(mqtt_pub_topic,"{\"method\":\"thing.service.property.set\",\"id\":\"421321722\",\"params\":{\"Flame_State\":0},\"version\":\"1.0.0\"}");
                btn_flame.setImageResource(R.drawable.flame);
                makeToast("结束检测火焰");
                fan_flag=0;
            }
        });
    }
    private void btnSmog() {
        btn_smog.setOnClickListener(v -> {
            if (fan_flag==0){  //{"method":"thing.service.property.set","id":"421321722","params":{"SprayPumpStatus":0,"FanRun":0,"SmokeSensorState":0,"Flame_State":0,"Buzzer":0},"version":"1.0.0"}
                publishMessage(mqtt_pub_topic,"{\"method\":\"thing.service.property.set\",\"id\":\"421321722\",\"params\":{\"SmokeSensorState\":1},\"version\":\"1.0.0\"}");
                btn_smog.setImageResource(R.drawable.smog2);
                makeToast("开始检测烟雾");
                fan_flag=1;
            }else {
                publishMessage(mqtt_pub_topic,"{\"method\":\"thing.service.property.set\",\"id\":\"421321722\",\"params\":{\"SmokeSensorState\":0},\"version\":\"1.0.0\"}");
                btn_smog.setImageResource(R.drawable.smog);
                makeToast("结束检测烟雾");
                fan_flag=0;
            }
        });
    }
    private void btnFan() {
        btn_fan.setOnClickListener(v -> {
            if (fan_flag==0){  //{"method":"thing.service.property.set","id":"421321722","params":{"SprayPumpStatus":0,"FanRun":0,"SmokeSensorState":0,"Flame_State":0,"Buzzer":0},"version":"1.0.0"}
                publishMessage(mqtt_pub_topic,"{\"method\":\"thing.service.property.set\",\"id\":\"421321722\",\"params\":{\"FanRun\":1},\"version\":\"1.0.0\"}");
                btn_fan.setImageResource(R.drawable.fan2);
                makeToast("打开风扇");
                fan_flag=1;
            }else {
                publishMessage(mqtt_pub_topic,"{\"method\":\"thing.service.property.set\",\"id\":\"421321722\",\"params\":{\"FanRun\":0},\"version\":\"1.0.0\"}");
                btn_fan.setImageResource(R.drawable.fan);
                makeToast("关闭风扇");
                fan_flag=0;
            }
        });
    }
    private void btnBuzzer() {
        btn_buzzer.setOnClickListener(v -> {
            if (fan_flag==0){  //{"method":"thing.service.property.set","id":"421321722","params":{"SprayPumpStatus":0,"FanRun":0,"SmokeSensorState":0,"Flame_State":0,"Buzzer":0},"version":"1.0.0"}
                publishMessage(mqtt_pub_topic,"{\"method\":\"thing.service.property.set\",\"id\":\"421321722\",\"params\":{\"Buzzer\":1},\"version\":\"1.0.0\"}");
                btn_buzzer.setImageResource(R.drawable.buzzer2);
                makeToast("打开蜂鸣器");
                fan_flag=1;
            }else {
                publishMessage(mqtt_pub_topic,"{\"method\":\"thing.service.property.set\",\"id\":\"421321722\",\"params\":{\"Buzzer\":0},\"version\":\"1.0.0\"}");
                btn_buzzer.setImageResource(R.drawable.buzzer);
                makeToast("关闭蜂鸣器");
                fan_flag=0;
            }
        });
    }
    private void btnWater() {
        btn_water_pump.setOnClickListener(v -> {
            if (fan_flag==0){  //{"method":"thing.service.property.set","id":"421321722","params":{"SprayPumpStatus":0,"FanRun":0,"SmokeSensorState":0,"Flame_State":0,"Buzzer":0},"version":"1.0.0"}
                publishMessage(mqtt_pub_topic,"{\"method\":\"thing.service.property.set\",\"id\":\"421321722\",\"params\":{\"SprayPumpStatus\":1},\"version\":\"1.0.0\"}");
                btn_water_pump.setImageResource(R.drawable.water_pump2);
                makeToast("打开水泵");
                fan_flag=1;
            }else {
                publishMessage(mqtt_pub_topic,"{\"method\":\"thing.service.property.set\",\"id\":\"421321722\",\"params\":{\"SprayPumpStatus\":0},\"version\":\"1.0.0\"}");
                btn_water_pump.setImageResource(R.drawable.water_pump);
                makeToast("关闭水泵");
                fan_flag=0;
            }
        });
    }

    public void mqtt_init_Connect()
    {
        final String serverUri = "tcp://iot-06z00d2jpm7ltqv.mqtt.iothub.aliyuncs.com:1883";     //物联网云平台的域名+1883端口号
        String userName=getSharedPreferences("myfile",0).getString("name","");      //用户名//edt_user.getText().toString(),"APP_demo&k1g4ohPpMe7"
        String passWord=getSharedPreferences("myfile",0).getString("pwd","");       //密码edt_pwd.getText().toString(),"748497b3e52670f1425aea8921085faa686f59b904d8a3ac1a0fd50a312df93b"
        String clientId=getSharedPreferences("myfile",0).getString("clientId","");  //密钥 edt_clientId.getText().toString(),"k1g4ohPpMe7.APP_demo|securemode=2,signmethod=hmacsha256,timestamp=1718789534125|"
        try {
            //实例化mqtt_client，填入我们定义的serverUri和clientId，然后MemoryPersistence设置clientid的保存形式，默认为以内存保存
            mqtt_client = new MqttClient(serverUri,clientId,new MemoryPersistence());
            //创建并实例化一个MQTT的连接参数对象
            options = new MqttConnectOptions();
            //设置是否清空session,设置为false表示服务器会保留客户端的连接记录，设置为true表示每次连接到服务器都以新的身份连接
            options.setCleanSession(false);
            //然后设置对应的参数
            options.setUserName(userName);                  //设置连接的用户名
            options.setPassword(passWord.toCharArray());    //设置连接的密码
            options.setConnectionTimeout(30);               //设置超时时间，单位为秒
            options.setKeepAliveInterval(50);               //设置心跳,30s
            options.setAutomaticReconnect(true);            //是否重连

            //设置回调
            mqtt_client.setCallback(new MqttCallback() {
                @Override
                public void connectionLost(Throwable cause) {
                    //连接丢失后，一般在这里面进行重连
                    makeToast("connectionLost");
                }
                @Override
                public void deliveryComplete(IMqttDeliveryToken token) {
                    //publish后会执行到这里
                }
                @Override
                public void messageArrived(String topicName, MqttMessage message) {
                    //subscribe后得到的消息会执行到这里面
                    Message msg=new Message();
                    msg.what=3;                 //收到消息标志位
                    msg.obj=topicName+"---"+message.toString();
                    handler.sendMessage(msg);                           //回传
                }
            });

            //连接mqtt服务器
            //mqtt_client.connect(options);         //启动

        }catch (Exception e) {
            e.printStackTrace();
            makeToast(e.toString());        //提示错误
        }
    }
    private void mqtt_connect(){
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (!(mqtt_client.isConnected())) {      //如果还未连接
                        mqtt_client.connect(options);
                        Message msg=new Message();
                        msg.what=31;                          //连接成功
                        handler.sendMessage(msg);
                    }

                }catch (Exception e){
                    e.printStackTrace();
                    Message msg=new Message();
                    msg.what=30;                              //连接失败
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }

    public void startReconnect() {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
                if (!mqtt_client.isConnected()){
                     mqtt_connect();
                }
            }
        },0*1000,10*1000, TimeUnit.MILLISECONDS);
    }

    private ScheduledExecutorService scheduler;
    public void publishMessage(String topic,String message_str){
        try {
            MqttMessage message = new MqttMessage();
            message.setPayload(message_str.getBytes());
            if(mqtt_client.isConnected()){
                mqtt_client.publish(topic, message);
            }
        } catch (MqttException e) {
            e.printStackTrace();
        }
    }
    //提示信息
    private void makeToast(String toast_str) {
        Toast.makeText(EquipmentActivity.this, toast_str, Toast.LENGTH_SHORT).show();
    }
}